﻿using iMES.Core.Extensions;
using iMES.Core.Utilities;
using iMES.Custom.IRepositories;
using iMES.Entity.DomainModels;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using YUN.Ware.IRepositroies;

namespace YUN.Ware.Services
{
    public partial class Ware_ReservoirServices
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IWare_ReservoirRepository _repository;//访问数据库
        private readonly IBase_NumberRuleRepository _numberRuleRepository;//自定义编码规则访问数据库
        [ActivatorUtilitiesConstructor]

        public Ware_ReservoirServices(IHttpContextAccessor httpContextAccessor, IWare_ReservoirRepository repository, IBase_NumberRuleRepository numberRuleRepository) : base(repository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = repository;
            _numberRuleRepository = numberRuleRepository;
        }
        WebResponseContent webResponse = new WebResponseContent();
        /// <summary>
        /// 新建
        /// </summary>
        /// <param name="saveDataModel"></param>
        /// <returns></returns>
        public override WebResponseContent Add(SaveModel saveDataModel)
        {
            //此处saveModel是从前台提交的原生数据，可对数据进修改过滤
            AddOnExecuting = (Ware_Reservoir tool, object list) =>
            {
                if (string.IsNullOrWhiteSpace(tool.ReserCode))
                    tool.ReserCode = GetToolCode();
                //如果返回false,后面代码不会再执行
                if (repository.Exists(x => x.ReserCode == tool.ReserCode))
                {
                    return webResponse.Error("库区编码已存在");
                }
                return webResponse.OK();
            };
            return base.Add(saveDataModel);
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="saveDataModel"></param>
        /// <returns></returns>
        public override WebResponseContent Update(SaveModel saveDataModel)
        {
            //此处saveModel是从前台提交的原生数据，可对数据进修改过滤
            AddOnExecuting = (Ware_Reservoir tool, object list) =>
            {
                if (string.IsNullOrWhiteSpace(tool.ReserCode))
                    tool.ReserCode = GetToolCode();
                //如果返回false,后面代码不会再执行
                if (repository.Exists(x => x.ReserCode == tool.ReserCode))
                {
                    return webResponse.Error("仓库编码已存在");
                }
                return webResponse.OK();
            };
            return base.Update(saveDataModel);
        }
        /// <summary>
        /// 自动生成设备编号
        /// </summary>
        /// <returns></returns>
        public string GetToolCode()
        {
            //查询当天最新的订单号
            string defectItemCode = repository.FindAsIQueryable(x => x.ReserCode.Length > 8)
                .OrderByDescending(x => x.ReserCode)
                .Select(s => s.ReserCode)
                .FirstOrDefault();
            Base_NumberRule numberRule = _numberRuleRepository.FindAsIQueryable(x => x.FormCode == "Tool")
                .OrderByDescending(x => x.CreateDate)
                .FirstOrDefault();
            if (numberRule != null)
            {
                // 构建基础规则部分：前缀 + 时间格式
                string rule = numberRule.Prefix + DateTime.Now.ToString(numberRule.SubmitTime.Replace("hh", "HH"));

                // 处理序列号部分
                if (string.IsNullOrEmpty(defectItemCode))
                {
                    // 如果没有提供上一个编号，从1开始
                    rule += "1".PadLeft(numberRule.SerialNumber, '0');
                }
                else
                {
                    // 从现有编号中提取最后几位数字并加1
                    string serialPart = defectItemCode.Substring(Math.Max(0, defectItemCode.Length - numberRule.SerialNumber));
                    int nextSerial = serialPart.GetInt() + 1;
                    rule += nextSerial.ToString("0".PadLeft(numberRule.SerialNumber, '0'));
                }

                return rule;
            }
            else //如果自定义序号配置项不存在，则使用日期生成
            {
                return DateTime.Now.ToString("yyyyMMddHHmmssffff");
            }
        }
    }
}
